package org.langqiao.network;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class TestGetPost {

	public static void main(String[] args) {
		String s = TestGetPost.sendPost("http://localhost:8082/CcAppNew/workOrder/helpWorkOrder/tohelpWorkOrderListPage.action" , null);
		System.out.println(s);
		String s1 = TestGetPost.sendGet("https://cas3:443/cas/logout?service=http://localhost:8082/CcAppNew/" , null);
		System.out.println(s1);
	}

	//像web站点发送post请求
	public static String sendPost(String url , String param){
		String result = "";
		BufferedReader in = null;
		PrintWriter out = null;
		try{
			URL readUrl = new URL(url);
			URLConnection conn = readUrl.openConnection();
			
			//设置通用请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
			conn.setDoInput(true);
			conn.setDoOutput(true);

			out = new PrintWriter(conn.getOutputStream());
			out.print(param);
			out.flush();
			
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null ; 
			while((line = in.readLine()) != null){
				result += "\n" +line ;
			}
		}catch(Exception e){
			System.out.println("发送pos请求发生异常："+e);
			e.printStackTrace();
		}
		return result;
	}

	//像web站点发送get请求
	public static String sendGet(String url , String param){
		String result = "";
		BufferedReader in = null;
		try{
			String urlName = url + "?" + param ;
			URL readUrl = new URL(urlName);
			URLConnection conn = readUrl.openConnection();
			
			//设置通用请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
			
			//建立连接
			conn.connect();
			
			Map<String , List<String>> map = conn.getHeaderFields();
			for(String key : map.keySet()){
				System.out.println(key + "------>" + map.get(key));
			}
			
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			
			String line = null ; 
			while((line = in.readLine()) != null){
				result += "\n" +line ;
			}
		}catch(Exception e){
			System.out.println("发送Get请求发生异常："+e);
			e.printStackTrace();
		}
		return result;
	}
}
